#include "MotorConfig.h"
#include <QSettings>
#include <QDebug>
#include <QFileInfo>
#include <QDir>

// 静态成员初始化
MotorConfig* MotorConfig::instance = nullptr;
const QString MotorConfig::ConnectionDefaults::DEFAULT_IP_ADDRESS = "192.168.0.30";

MotorConfig* MotorConfig::getInstance() {
    if (instance == nullptr) {
        instance = new MotorConfig();
    }
    return instance;
}

void MotorConfig::destroyInstance() {
    if (instance != nullptr) {
        delete instance;
        instance = nullptr;
    }
}

MotorConfig::MotorConfig() {
    // resetToDefaults();
}

void MotorConfig::resetToDefaults() {
    // FuYu电机配置
    m_motorMaxTravel = FuYuMotorDefaults::MOTOR_MAX_TRAVEL;
    m_opticalPathMin = FuYuMotorDefaults::OPTICAL_PATH_MIN;
    m_opticalPathMax = FuYuMotorDefaults::OPTICAL_PATH_MAX;
    m_safetyMargin = FuYuMotorDefaults::SAFETY_MARGIN;

    // 运动参数
    m_defaultSpeed = MotionDefaults::DEFAULT_SPEED;
    m_defaultAcceleration = MotionDefaults::DEFAULT_ACCELERATION;
    m_defaultDeceleration = MotionDefaults::DEFAULT_DECELERATION;
    m_homeSpeed = MotionDefaults::HOME_SPEED;
    m_homeAccDec = MotionDefaults::HOME_ACC_DEC;
    m_homeFallStep = MotionDefaults::HOME_FALL_STEP;

    // 连接参数
    m_defaultIpAddress = ConnectionDefaults::DEFAULT_IP_ADDRESS;
    m_defaultPort = ConnectionDefaults::DEFAULT_PORT;
    m_defaultDeviceId = ConnectionDefaults::DEFAULT_DEVICE_ID;
    m_defaultAxis = ConnectionDefaults::DEFAULT_AXIS;

    qDebug() << "MotorConfig: 配置已重置为默认值";
}

void MotorConfig::loadFromFile(const QString& filePath) {
    QFileInfo fileInfo(filePath);
    if (!fileInfo.exists()) {
        qDebug() << "MotorConfig: 配置文件不存在，使用默认配置:" << filePath;
        resetToDefaults();
        saveToFile("config/motor_config.ini");
        return;
    }

    QSettings settings(filePath, QSettings::IniFormat);
    
    // 读取FuYu电机配置
    settings.beginGroup("FuYuMotor");
    // 优先读取新的配置键名，如果不存在则使用旧键名作为回退
    m_motorMaxTravel = settings.value("MotorMaxTravel", 
        settings.value("MaxPosition", FuYuMotorDefaults::MOTOR_MAX_TRAVEL).toDouble()).toDouble();
    m_opticalPathMin = settings.value("OpticalPathMin", 
        settings.value("InitPosition", FuYuMotorDefaults::OPTICAL_PATH_MIN).toDouble()).toDouble();
    m_opticalPathMax = settings.value("OpticalPathMax", 
        settings.value("MeasurementMaxPosition", FuYuMotorDefaults::OPTICAL_PATH_MAX).toDouble()).toDouble();
    m_safetyMargin = settings.value("SafetyMargin", FuYuMotorDefaults::SAFETY_MARGIN).toDouble();
    settings.endGroup();

    // 读取运动参数
    settings.beginGroup("Motion");
    m_defaultSpeed = settings.value("DefaultSpeed", MotionDefaults::DEFAULT_SPEED).toDouble();
    m_defaultAcceleration = settings.value("DefaultAcceleration", MotionDefaults::DEFAULT_ACCELERATION).toDouble();
    m_defaultDeceleration = settings.value("DefaultDeceleration", MotionDefaults::DEFAULT_DECELERATION).toDouble();
    m_homeSpeed = settings.value("HomeSpeed", MotionDefaults::HOME_SPEED).toDouble();
    m_homeAccDec = settings.value("HomeAccDec", MotionDefaults::HOME_ACC_DEC).toDouble();
    m_homeFallStep = settings.value("HomeFallStep", MotionDefaults::HOME_FALL_STEP).toDouble();
    settings.endGroup();

    // 读取连接参数
    settings.beginGroup("Connection");
    m_defaultIpAddress = settings.value("DefaultIpAddress", ConnectionDefaults::DEFAULT_IP_ADDRESS).toString();
    m_defaultPort = settings.value("DefaultPort", ConnectionDefaults::DEFAULT_PORT).toInt();
    m_defaultDeviceId = settings.value("DefaultDeviceId", ConnectionDefaults::DEFAULT_DEVICE_ID).toInt();
    m_defaultAxis = settings.value("DefaultAxis", ConnectionDefaults::DEFAULT_AXIS).toInt();
    settings.endGroup();

    // 验证配置
    if (!validateConfiguration()) {
        qWarning() << "MotorConfig: 配置验证失败，错误信息:" << getConfigurationError();
        qWarning() << "MotorConfig: 恢复默认配置";
        resetToDefaults();
    } else {
        qDebug() << "MotorConfig: 配置文件加载成功:" << filePath;
    }
}

void MotorConfig::saveToFile(const QString& filePath) const {
    // 确保目录存在
    QFileInfo fileInfo(filePath);
    QDir dir = fileInfo.absoluteDir();
    if (!dir.exists()) {
        dir.mkpath(dir.absolutePath());
    }

    QSettings settings(filePath, QSettings::IniFormat);
    
    // 保存FuYu电机配置
    settings.beginGroup("FuYuMotor");
    settings.setValue("MotorMaxTravel", m_motorMaxTravel);
    settings.setValue("OpticalPathMin", m_opticalPathMin);
    settings.setValue("OpticalPathMax", m_opticalPathMax);
    settings.setValue("SafetyMargin", m_safetyMargin);
    settings.endGroup();

    // 保存运动参数
    settings.beginGroup("Motion");
    settings.setValue("DefaultSpeed", m_defaultSpeed);
    settings.setValue("DefaultAcceleration", m_defaultAcceleration);
    settings.setValue("DefaultDeceleration", m_defaultDeceleration);
    settings.setValue("HomeSpeed", m_homeSpeed);
    settings.setValue("HomeAccDec", m_homeAccDec);
    settings.setValue("HomeFallStep", m_homeFallStep);
    settings.endGroup();

    // 保存连接参数
    settings.beginGroup("Connection");
    settings.setValue("DefaultIpAddress", m_defaultIpAddress);
    settings.setValue("DefaultPort", m_defaultPort);
    settings.setValue("DefaultDeviceId", m_defaultDeviceId);
    settings.setValue("DefaultAxis", m_defaultAxis);
    settings.endGroup();

    settings.sync();
    qDebug() << "MotorConfig: 配置已保存到文件:" << filePath;
}

bool MotorConfig::validateConfiguration() const {
    // 基本范围检查
    if (m_motorMaxTravel <= 0) return false;
    if (m_opticalPathMin < 0) return false;
    if (m_opticalPathMax <= m_opticalPathMin) return false;
    if (m_safetyMargin < 0) return false;

    // 运动参数检查
    if (m_defaultSpeed <= 0) return false;
    if (m_defaultAcceleration <= 0) return false;
    if (m_defaultDeceleration <= 0) return false;
    if (m_homeSpeed <= 0) return false;
    if (m_homeAccDec <= 0) return false;
    if (m_homeFallStep < 0) return false;

    // 连接参数检查
    if (m_defaultPort <= 0 || m_defaultPort > 65535) return false;
    if (m_defaultDeviceId < 0 || m_defaultDeviceId > 255) return false;
    if (m_defaultAxis < 0 || m_defaultAxis > 7) return false;

    // 逻辑一致性检查
    double calculatedMax = getCalculatedOpticalPathMax();
    if (m_opticalPathMax > calculatedMax + m_safetyMargin) return false;

    return true;
}

QString MotorConfig::getConfigurationError() const {
    if (m_motorMaxTravel <= 0) return "电机最大行程必须大于0";
    if (m_opticalPathMin < 0) return "光路最小位置不能为负";
    if (m_opticalPathMax <= m_opticalPathMin) return "光路最大位置必须大于最小位置";
    if (m_safetyMargin < 0) return "安全边界不能为负";

    if (m_defaultSpeed <= 0) return "默认速度必须大于0";
    if (m_defaultAcceleration <= 0) return "默认加速度必须大于0";
    if (m_defaultDeceleration <= 0) return "默认减速度必须大于0";
    if (m_homeSpeed <= 0) return "回零速度必须大于0";
    if (m_homeAccDec <= 0) return "回零加减速度必须大于0";
    if (m_homeFallStep < 0) return "脱落距离不能为负";

    if (m_defaultPort <= 0 || m_defaultPort > 65535) return "端口号必须在1-65535范围内";
    if (m_defaultDeviceId < 0 || m_defaultDeviceId > 255) return "设备ID必须在0-255范围内";
    if (m_defaultAxis < 0 || m_defaultAxis > 7) return "轴号必须在0-7范围内";

    double calculatedMax = getCalculatedOpticalPathMax();
    if (m_opticalPathMax > calculatedMax + m_safetyMargin) {
        return QString("光路最大位置(%1)超出安全范围(%2)")
                .arg(m_opticalPathMax)
                .arg(calculatedMax + m_safetyMargin);
    }

    return "配置正常";
}
